let callbacks = []

function loadedTinymce() {
  return window.tinymce
}

const dynamicLoadScript = (path, callback) => {
  const existingScript = document.getElementById(path)
  const func = callback || function() {}

  if (!existingScript) {
    const script = document.createElement('script')
    script.src = path
    script.id = path
    document.body.appendChild(script)

    callbacks.push(func)
    const onEnd = 'onload' in script ? stdOnEnd : ieOnEnd
    onEnd(script)
  }

  if (existingScript && func) {
    if (loadedTinymce()) {
      func(null, existingScript)
    } else {
      callbacks.push(func)
    }
  }

  function stdOnEnd(script) {
    script.onload = function () {
      this.onerror = this.onload = null

      for (const func of callbacks) {
        func(null, script)
      }
      callbacks = []
    }
    script.onerror = function () {
      this.onerror = this.onload = null
      func(new Error('Failed to load' + script), script)
    }
  }
  function ieOnEnd(script) {
    script.onreadystatechange = function () {
      if (this.readyState !== 'complete' && this.readyState !== 'loaded') return

      this.onreadystatechange = null

      for (const func of callbacks) {
        func(null, script)
      }
      callbacks = []
    }
  }
}

export default dynamicLoadScript
